<?php

namespace yphp;

class Random extends Instance
{

    //+----------------------------------------------------------------------
    //  构造函数：初始化节点信息
    //+----------------------------------------------------------------------

    function construct($nodes)
    {
        // 随机数倍率
        $this->times = Config::web('data_node_rate');
        foreach ($nodes as $node => $num) {
            $this->sum += $num;
            $this->len++;
        }
        $this->nodes = $nodes;
    }

    //+----------------------------------------------------------------------
    //  节点数组
    //+----------------------------------------------------------------------

    private $nodes = [];

    //+----------------------------------------------------------------------
    //  随机数倍率
    //+----------------------------------------------------------------------

    private $times;

    //+----------------------------------------------------------------------
    //  节点数量
    //+----------------------------------------------------------------------

    private $len = 0;

    //+----------------------------------------------------------------------
    //  虚节点数量
    //+----------------------------------------------------------------------

    private $sum = 0;

    //+----------------------------------------------------------------------
    //  获取节点
    //+----------------------------------------------------------------------

    function getNode()
    {
        if ($this->len === 1) return key($this->nodes);
        $rand = mt_rand(1, $this->sum * $this->times) % $this->sum;
        foreach ($this->nodes as $node => $num) {
            if ($num > $rand) return $node;
            $rand -= $num;
        }
        return false;
    }


}